import { createStore, applyMiddleware } from 'redux'
import createSaga from 'redux-saga'
import { takeEvery, put, delay, call } from 'redux-saga/effects'
import rootSaga from './saga'


// 1. saga = createSaga()  添加到applyMiddleware中
// 2. saga.run(*函数)  .run 要在使用中间件之后来执行
const saga = createSaga()

const reducer = (state, { type, list }) => {
    const NewState = JSON.parse(JSON.stringify(state))

    switch (type) {
        case 'ADD_NUM':
            NewState.num += 1
            return NewState
        case 'DEL_NUM':
            NewState.num -= 1
            return NewState
        case 'SET_LIST':
            NewState.list = list
            return NewState
        default:
            return state
    }
}

const initState = {
    num: 1000,
    count: 888,
    list: []
}

// takeEvery  开启任务
// delay  模拟延时器
// put  代替 dispatch
// call 发起请求

// function* rootSaga() {
//     yield takeEvery("ASYNC_ADD_NUM", changeNum)
//     yield takeEvery("ASYNC_CHANGE_LIST", changeList)
// }

// function* changeNum() {
//    yield delay(1000)
//    yield put({ type: 'ADD_NUM' })
// }

// function* changeList() {
//     // call()
//     const data = yield call(axios.get, 'https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata')
//     yield put({ type: "SET_LIST", list: data.data.message })
//  }

let store = createStore(reducer, initState, applyMiddleware(saga))

saga.run(rootSaga)

export default store